/**
 * @file dataResource.js
 * @Date 2023-10-17, 周二, 15:42
 * @description 文件说明
 * 数据资源市场js文件
 */

$(function () {
    /******************************************初始化******************************************/
    // 查询目录参数
    let fieldParams = {
        currPage: 1,
        pageSize: 8,
        keyword: "",
        catalogTypes: '0,2', //资源和都适用
        systemCatalogId: 10000,//服务门户
        parentId: null//父级目录
    }
    // 资源列表请求参数
    let resourceParams = {
        currPage: 0,
        pageSize: 8,
        contentName: "",//根据名字模糊查询
        // systemCatalogId: 10000,//服务门户
        systemFieldId: null,//分类id
        status:0
    }
    // 分页页数
    // let pageNumber=0;
    /******************************************事件处理部分******************************************/
    // 点击使用分类，渲染子级分类和产品列表
    $('.ServiceMenu').on('click', '.ServiceMenuItem', function () {
        // 控制点击后的颜色改变
        for (let i = 0; i < $(this).parent().find('.card-header').length; i++) {
            if ($(this).parent().find('.card-header')[i] == $(this).find('.card-header')[0]) {
                $(this).find('.card-header').attr('style', 'background-color: #0ac382;color: #fff;')
            } else {
                $(this).parent().find('.card-header')[i].style.removeProperty("background")
                $(this).parent().find('.card-header')[i].style.removeProperty("color")
            }
        }
        $("#resourcesTypeTitle").text($(this).find('.card-header').html());
        const id = $(this).find('.card-header').attr('data-ID')
        fieldParams.parentId = id;
        fieldReq(fieldParams).then(res => {
            sonFieldRender(res.data)
        })
        resourceParams.systemFieldId=id;
        dataSourceRender(resourceParams)
    })

    // 子级目录点击事件
    // 点击使用分类，渲染子级分类和产品列表
    $('.sonMenu').on('click', '.sonMenuItem', function () {
        console.log('点击使用分类 ',$(this).find('.card-header').attr('data-ID'))
        // 控制点击后的颜色改变
        for (let i = 0; i < $(this).parent().find('.card-header').length; i++) {
            if ($(this).parent().find('.card-header')[i] == $(this).find('.card-header')[0]) {
                $(this).find('.card-header').attr('style', 'background-color: #0ac382;color: #fff;')
            } else {
                $(this).parent().find('.card-header')[i].style.removeProperty("background")
                $(this).parent().find('.card-header')[i].style.removeProperty("color")
            }
        }
        // console.log('this', $(this).html())
        resourceParams.systemFieldId=$(this).find('.card-header').attr('data-ID');
        dataSourceRender(resourceParams)
    })

    //// 输入关键词搜索 回车搜索
    $('#input').bind('keypress', function (e) {
        if (e.keyCode === 13) {
            // 获取搜索框输入的搜索内容
            let content = $(this)[0].value;
            console.log('content关键词', content)
            if (content == null) {
                dataSourceRender(resourceParams)
            } else {
                resourceParams.keyword = content
                dataSourceRender(resourceParams)
            }
        }
    })

    // 导航栏点击事件
    $('.nav3 .nav-item a').click(function (e) {
        e.preventDefault();
        $(".nav3 .nav-item a").removeClass('active1')
        $(this).addClass("active1")
    })

    // 点击排序
    $('.searchbar a').on('click', function () {
        if ($(this).html() === '综合排序') {
            resourceParams.sortField = ''
            dataSourceRender(resourceParams)
        } else if ($(this).html() === '最近更新') {
            resourceParams.sortField = 'update_time desc'
            dataSourceRender(resourceParams)
        } else if ($(this).html() === '最高人气') {
            resourceParams.sortField = 'visit_count desc'
            dataSourceRender(resourceParams)
        } else if ($(this).html() === '最好评价') {
            resourceParams.sortField = 'score desc'
            dataSourceRender(resourceParams)
        }

    })
    // 点击资源跳转到详情页面
    $(".dataResource").delegate(".card", "click", function () {
        let dataId = $(this).attr("data-ID");
        //let Type = $(this).attr("data-TYPE");
        window.location.href = './dataStoreDetial.html?sourceId=' + dataId;
    });
    // // 分页相关
    // // 分页(点击数字)
    // $('.pagination').on('click', '.pageN', function (e) {
    //     e.preventDefault()
    //     // 获取页数
    //     resourceParams.currPage = $(this)[0].innerHTML
    //     resourceReq(resourceParams).then(res=>{
    //         resourceListRender(res.rows)
    //     });// 发送请求
    // })
    // // 分页(上一页)
    // $('.pagination').on('click', '.previous', function (e) {
    //     e.preventDefault()
    //     // 获取当前页数
    //     let num = $(this).siblings('.active')[0].children[0].innerHTML;
    //     if (num > 1) {
    //         num -= 1;
    //         resourceParams.currPage = num
    //         resourceReq(resourceParams).then(res=>{
    //             resourceListRender(res.rows)
    //         });// 发送请求
    //     }
    // })
    // // 分页(下一页)
    // $('.pagination').on('click', '.next', function (e) {
    //     e.preventDefault()
    //     // 获取当前页数
    //     let num = $(this).siblings('.active')[0].children[0].innerHTML;
    //     if (num <= pageNumber) {
    //         num -= -1;
    //         resourceParams.currPage = num
    //         resourceReq(resourceParams).then(res=>{
    //             resourceListRender(res.rows)
    //         });// 发送请求
    //     }
    // })

    /******************************************功能函数部分******************************************/
    /**
     * @description:渲染第一级分类部分
     * @return 返回值
     * @param data {Array} 目录列表数组
     */
    function fieldRender(data) {
        let moreData = []//更多目录信息
        let imgUrl = "./assets/img/demo/product_1.png";
        data.forEach((val, index) => {
            if (index < 7) {
                switch (index) {
                    case 0:
                        imgUrl = "./assets/img/demo/product_1.png";
                        break;
                    case 1:
                        imgUrl = "./assets/img/demo/product_2.png";
                        break;
                    case 2:
                        imgUrl = "./assets/img/demo/product_3.png";
                        break;
                    case 3:
                        imgUrl = "./assets/img/demo/product_4.png";
                        break;
                    case 4:
                        imgUrl = "./assets/img/demo/product_5.png";
                        break;
                    case 5:
                        imgUrl = "./assets/img/demo/product_6.png";
                        break;
                    case 6:
                        imgUrl = "./assets/img/demo/product_7.png";
                        break;
                    default:
                        break;
                }
                let html = `<div class="card info border-0 shadow-sm ServiceMenuItem" ">
                  <div class="card-body">
                    <img class="d-block w-100" src="` + imgUrl + `" alt="` + val.fieldName + `">
                  </div>
                  <div class="card-header border-0 pt-4 pb-4" data-ID="${val.id}" data-TYPE="${val.type}>
                    <h3 class="my-0 font-weight-normal">${val.fieldName}</h3>
                  </div>
                </div>`
                $('.ServiceMenu').append(html);
                $("#resourcesTypeTitle").text(data[0].fieldName);
            } else {
                let data = {
                    id: val.id,
                    typeName: val.fieldName
                }
                moreData.push(data)
                let html = `<div class="card moreInfo border-0 shadow-sm">
                <div class="card-body">
                  <img class="d-block w-100" src="./assets/img/demo/product_8.png" alt="更多分类">
                </div>
                <div class="card-header border-0 pt-4 pb-4">
                  <h3 class="my-0 font-weight-normal">更多分类</h3>
                </div>
              </div>`
                $(".ServiceMenu").append(html);
            }
        })
    }
    /**
     * @description:渲染子级分类
     * @return 返回值
     * @param data  {Array} 目录列表数组
     */
    function sonFieldRender(data) {
        $('.sonMenu').empty()
        data.forEach((val, index) => {
            let html = `<div class="info border-0 shadow-sm sonMenuItem"  style="margin-left:15px;">
									<div class="card-header border-0 pt-2 pb-2" data-ID="${val.id}" data-TYPE="${val.type}">
										<h3 class="my-0 font-weight-normal">${val.fieldName}</h3>
									</div>
								</div>`
            $('.sonMenu').append(html)
        })
    }
    /**
     * @description:目录请求
     * @return {Promise} 请求的结果
     * @param fieldParams {Object} 目录查询参数
     */
    function fieldReq(fieldParams) {
        return new Promise(function (resolve, reject) {
            $.ajax({
       timeout:30000,
                url: window.Http + '/customer/fieldType/list',
                type: "GET",
                headers: {
                    'Authorization': "Bearer " + sessionStorage.getItem('Token')
                },
                data: fieldParams,
                success: function (res) {
                    if (res.code === 200) {
                        resolve(res); // 成功时将响应传递给调用者
                    } else {
                        layer.msg(res.msg)
                        reject(new Error("请求失败")); // 失败时将错误传递给调用者
                    }
                }
            })
        })
    }
    /**
     * @description:数据资源请求
     * @return {Promise} 请求的结果
     * @param params {Object} 请求参数
     */
    function resourceReq(params) {
        return new Promise((function (resolve, reject) {
            $.ajax({
       timeout:30000,
                url: window.Http + '/customer/datasourceContent/list',
                type: "GET",
                headers: {
                    'Authorization': "Bearer " + sessionStorage.getItem('Token')
                },
                data: params,
                success: function (res) {
                    if (res.code === 200) {
                        resolve(res)
                    } else {
                        reject(new Error("请求失败")); // 失败时将错误传递给调用者
                        layer.msg(res.msg)
                    }
                }
            })
        }))
    }
    /**
     * @description:数据资源展示列表和分页渲染
     * @return 返回值
     * @param parame {Object}  数据资源请求参数
     */
    function dataSourceRender(parame){
        resourceReq(parame).then(res=>{
            resourceListRender(res.rows)
            layui.laypage.render({
                elem: 'DataResourcesPage', //注意，这里的 test1 是 ID，不用加 # 号
                count: res.total, //数据总数，从服务端得到
                limit: 8,
                groups: 5,
                jump: function (obj, first) {
                    if(!first){
                        console.log('obj.curr', obj.curr)
                        parame.currPage=obj.curr
                        resourceReq(parame).then(res=>{
                            resourceListRender(res.rows)
                        });
                    }
                }
            });
        })
    }
    /**
     * @description:数据资源列表渲染
     * @return 返回值
     * @param data {Array} 数据资源列表数组
     */
    function resourceListRender(data) {
        console.log('data', data)
        $(".dataResource").empty();
        if (data.length===0){
            $(".dataResource").append('<h3 style="margin: auto;">暂时没有数据！</h3>')
        }else {
            data.forEach(function (val, index) {
                let labelHtml = "";
                if (val.keyword) {
                    let keywordStr = val.keyword;
                    let reg = /\\|\/|\;|\;|\，|\,|\、|\、|\^|\`|\|/g;
                    keywordStr = keywordStr.replace(reg, ",");
                    let labels = keywordStr.split(',');
                    labels.forEach((item) => {
                        labelHtml += `<span style="border: 1px solid #0ac382;border-radius: 2px;font-size: 12px;color: #0ac382;line-height: 18px;margin-right: 6px;padding: 0 6px;">${item}</span>`
                    })
                }
                let num = (Math.ceil(val.score))*31;//模拟评分
                let keywords=''
               if (val.systemFieldList&&val.systemFieldList.length>0){
                   val.systemFieldList?.forEach((item,index)=>{
                       keywords+=`
                       <span style="border: 1px solid #0ac382;border-radius: 2px;font-size: 12px;color: #0ac382;line-height: 18px;margin-right: 6px;padding: 0 6px;">${item.keyWords.match(/[^,]+/g)[0]}</span>
                   `
                   })
               }else {
                   keywords=`
                       <span style="border: 1px solid #0ac382;border-radius: 2px;font-size: 12px;color: #0ac382;line-height: 18px;margin-right: 6px;padding: 0 6px;">暂无</span>
                  
                   `
               }
               let  html = `<div class="card shadow-sm border-0" data-ID="${val.id}" >
                                                <div class="card-header border-0">
                                                    <h3 class="my-0 font-weight-normal">${val.contentName}</h3>
                                                </div>
                                                <div class="card-body">
                                                    <ul class="list-unstyled mt-2 mb-2">
                                                        <li>
                                                            <div style="width: 100%;height: 135px;overflow: hidden;margin-bottom: 10px;"><img src="${val.iconUrl ? val.iconUrl:'./assets/img/demo/iconURL1.jpg'}" /></div>
                                                        </li>
                                                        <li>
                                                        ${keywords}
                                                        </li>
                                                        <li>
                                                            <span style="color: #8890a7;font-size:12px;margin-left: -7px;">
                                                        <div class="atar_Show">
                                                          <p tip="5" style="width:${num}px"></p>
                                                        </div>
                                                        <span></span>
                                                    </span>
                                                        </li>
                                                        <li>
                                                            <span style="color: #8890a7;font-size:12px;">提供方：${val.createBy}</span>
                                                        </li>
                                                        <li>
                                                            <span style="color: #8890a7;font-size:12px;">访问量：${val.viewNumber||0}</span>
                                                        </li>
                                                    </ul>
                                                </div>
                                            </div>`
                $(".dataResource").append(html);
            })
        }
    }
    // 初始化目录请求
    fieldReq(fieldParams).then(res => {
        fieldRender(res.data)
    })
    // 数据资源初始化渲染
    dataSourceRender(resourceParams)
    // // 分页处理
    // function renderPage(num, pages) {
    //     pages -= -1;
    //     pageNumber = Math.ceil(num / resourceParams.pageSize);
    //     let html = '';
    //     $('.pagination').empty();
    //     $('.pagination').append(`<li class="page-item previous"> <a class="page-link" href="#" aria-label="Previous">
    //       <span aria-hidden="true">&laquo;</span></a></li>
    //       <li class="page-item next"><a class="page-link" href="#" aria-label="Next"><span aria-hidden="true">&raquo;</span></a></li>`)
    //     for (var i = 1; i <= pageNumber; i++) {
    //         html += `<li class="page-item"><a class="page-link pageN" href="#">` + i + `</a></li>`
    //     }
    //     $('.pagination li:first-child').after(html)
    //     $('.pagination li:nth-child(' + pages + ')').addClass('active')
    // }

})